package org.bluweb.g4wicket.map;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.wicket.markup.html.IHeaderResponse;
import org.bluweb.g4wicket.G4WicketComponent;


@SuppressWarnings("serial")
public class GMap extends G4WicketComponent {

	private Map<String,String> options = new HashMap<String, String>();
	private List<Marker> markers = new ArrayList<Marker>();
	private boolean sensor;
	private Location center;
	private int zoom = 8;
	
	public GMap( String id ) {
		super(id);
	}

	@Override
	public void renderHead(IHeaderResponse response) {
		super.renderHead( response );
		response.renderJavascriptReference( "http://maps.google.com/maps/api/js?sensor=" + this.sensor );
	}	

	public GMap setCenter( Location center ) {
		this.center = center;
		return this;
	}
	
	public GMap setZoom( int zoom ) {
		this.zoom = zoom;
		return this;
	}

	public void addMarker( Marker marker ) {
		this.markers.add( marker );
	}
	
	@Override
	protected void onBeforeRender() {
		super.onBeforeRender();

		Map<String,Object> parameters = new HashMap<String,Object>();
		
		if( this.center != null ) {
			parameters.put( "center", "var center = new google.maps.LatLng(" + center.getLat() + "," + center.getLng() + ");" );
			options.put( "center", "center" );
		}
		
	    options.put( "zoom", String.valueOf( this.zoom ) ); 
	    options.put( "mapTypeId", "google.maps.MapTypeId.ROADMAP" );		
		
		StringBuilder builder = new StringBuilder();
		for( String name : options.keySet() ) {
			if( builder.length() > 0 ) {
				builder.append( ',' );
			}
			builder.append( name ).append( ":" );
			builder.append( options.get( name ) );
		}
		
		parameters.put( "options", builder.toString() );
		
		if( !this.markers.isEmpty() ) {
			builder = new StringBuilder();
			int index = 0;
			for( Marker marker : this.markers ) {
				index++;
				builder.append( "var markerPos" ).append( index ).append( " = new google.maps.LatLng(" );
				builder.append( marker.getPosition().getLat() ).append( "," ).append( marker.getPosition().getLng() );
				builder.append( ");" );
				
				builder.append( "var marker" ).append( index ).append( " = new google.maps.Marker({" );
				builder.append( "position: markerPos" ).append( index ).append( "," );
				if( marker.getImage() != null ) {
					builder.append( "icon: '" ).append( marker.getImage() ).append( "'," );
				}
				builder.append( "map: " ).append( this.getMarkupId() );
				builder.append( "});" );
			}
			parameters.put( "markers", builder.toString() );
		} else {
			parameters.put( "markers", "" );
		}
		
		
		this.setJavaScriptTemplate( "GMap.js", true, parameters );
	}
}
